package main

import (
	"fmt"
	"rpc_demo/stock_srv/utils/register"
	"sync"
	"time"
)

// redis分布式锁
func main() {
	// Create a pool with go-redis (or redigo) which is the pool redisync will
	// use while communicating with Redis. This can also be any pool that
	// implements the `redis.Pool` interface.
	//client := goredislib.NewClient(&goredislib.Options{
	//	Addr: "localhost:6379",
	//})
	//pool := goredis.NewPool(client) // or, pool := redigo.NewPool(...)

	// Create an instance of redisync to be used to obtain a mutual exclusion
	// lock.
	//rs := redsync.New(pool)

	redSync := register.New("localhost", 6379)

	// Obtain a new mutex by using the same name for all instances wanting the
	// same lock.

	mutexname := "my-global-mutex"
	gNum := 2
	var wg sync.WaitGroup
	wg.Add(gNum)
	for i := 0; i < gNum; i++ {
		defer wg.Done()
		mutex := redSync.Redsync.NewMutex(mutexname)

		fmt.Println("开始获取锁")
		// Obtain a lock for our given mutex. After this is successful, no one else
		// can obtain the same lock (the same mutex name) until we unlock it.
		if err := mutex.Lock(); err != nil {
			panic(err)
		}

		fmt.Println("获取锁成功")
		time.Sleep(time.Second * 3)
		// Do your work that requires the lock.

		// Release the lock so other processes or threads can obtain a lock.
		if ok, err := mutex.Unlock(); !ok || err != nil {
			panic("unlock failed")
		}
		fmt.Println("释放锁成功")
	}
	wg.Wait()

}
